<script lang="ts" setup name="consumerRebateEdit">
import { onMounted, reactive, ref } from "vue";
import { useRouter, useRoute } from "vue-router";
import HeaderCard from "./components/HeaderCard.vue";
import { activityQuantityType, ConsumerForm, DataType } from "@/types/createActivity";
import { getMemberGradeList } from "@/api/modules/member";
// import { getStoreList } from "@/api/modules/operation";
import { getFoodCouponList } from "@/api/modules/coupon";
import CouponDialog from "./components/CouponDialog.vue";
import { ElForm } from "element-plus";
import { getDateNow } from "@/utils/date";
import { createConsumerAPI, editConsumerAPI, getConsumerDetailAPI } from "@/api/modules/activity";
const router = useRouter();
const route = useRoute();
// const consumerForm = reactive<>();
// const rules = reactive();
const formRef = ref<InstanceType<typeof ElForm> | null>(null);
const onsubmit = async () => {
  await formRef.value?.validate();
  if (route.query.id) {
    await editConsumerAPI(consumerForm);
  } else {
    await createConsumerAPI(consumerForm);
  }
  router.push("/marketing/coupon-scan?upList=" + true);
};

const activityQuantityList = ref<activityQuantityType[]>([
  { name: "总限次", value: 0, type: false, prop: "total", isName: "isTotal" }, // type:1限制次数，0不限制
  { name: "每人限次", value: 0, type: false, prop: "userTotal", isName: "isUserTotal" },
  { name: "每人每天限次", value: 0, type: false, prop: "userDayStock", isName: "isUserDayStock" }
]);
// 修改限制次数
const onChangeQuantity = (idName: string, index: number) => {
  if (idName === "isTotal") {
    consumerForm.total = 0;
  } else if (idName === "isUserTotal") {
    consumerForm.userTotal = 0;
  } else {
    consumerForm.userDayStock = 0;
  }
};
const cycleData = reactive<DataType[]>([
  { label: "星期一", value: 1 },
  { label: "星期二", value: 2 },
  { label: "星期三", value: 3 },
  { label: "星期四", value: 4 },
  { label: "星期五", value: 5 },
  { label: "星期六", value: 6 },
  { label: "星期日", value: 7 }
]);

const consumerForm = reactive<ConsumerForm>({
  id: 0,
  path: "/marketing/consumer-rebate?id=",
  name: "",
  code: "",
  type: 4,
  validityRange: [getDateNow(0), getDateNow(1)],
  cycleValue: [],
  cycleType: 0,
  remark: "",
  rule: {
    ruleType: 1, // 1是消费满额赠可选多个规则 2 消费每满赠送只能赠送
    list: [
      {
        amount: 0,
        giftAmount: 0,
        isGiftAmount: false,
        isGiftCoupon: false,
        isGiftPoint: false,
        pointType: 2,
        pointValue: 0,
        couponList: []
      }
    ]
  },
  isTotal: false,
  total: 0,
  userDayStock: 0,
  userTotal: 0,
  isUserDayStock: false,
  isUserTotal: false,
  gradeType: 0,
  // storeType: 0,
  gradeList: [],
  // storeList: [],
  promotionType: 1
});
const rules: any = reactive({
  name: [{ required: true, message: "请输入活动名称" }],
  validityRange: [{ required: true, message: "请输入活动名称" }],
  cycleValue: [{ required: true, message: "请选择日期" }]
});
const validateAmount = (rule: any, value: any, callback: Function) => {
  // console.log(rule);

  if (value === 0) {
    callback(new Error("价格不能为0"));
  } else {
    callback();
  }
};
const giftAmountValidator = (rule: any, value: any, callback: Function) => {
  if (value === 0) {
    callback(new Error("价格不能为0"));
  } else {
    callback();
  }
};
const giftPointValidator = (rule: any, value: any, callback: Function) => {
  if (value === 0) {
    callback(new Error("价格不能为0"));
  } else if (isNaN(Number(value)) || Number(value) < 1) {
    callback(new Error("请输入正确的值"));
  } else {
    callback();
  }
};
// 修改可用日期
const onChangeCycle = () => {
  consumerForm.cycleValue = [];
};
// 修改赠送规则
// const onchangeRuleType = () => {
//   consumerForm.rule.list = [
//     {
//       amount: 0,
//       giftAmount: 0,
//       isGiftAmount: false,
//       isGiftCoupon: false,
//       isGiftPoint: false,
//       pointType: 2,
//       pointValue: 0,
//       couponList: []
//     }
//   ];
// };
const changeRuleList = (type: string, index: number) => {
  if (type === "ruleType") {
    consumerForm.rule.list = [
      {
        amount: 0,
        giftAmount: 0,
        isGiftAmount: false,
        isGiftCoupon: false,
        isGiftPoint: false,
        pointType: 2,
        pointValue: 0,
        couponList: []
      }
    ];
  } else if (type === "add") {
    if (consumerForm.rule.list.length > 9) return;
    consumerForm.rule.list.push({
      amount: 0,
      giftAmount: 0,
      isGiftAmount: false,
      isGiftCoupon: false,
      isGiftPoint: false,
      pointType: 2,
      pointValue: 0,
      couponList: []
    });
  } else {
    // 'del'
    if (consumerForm.rule.list.length <= 1) return;
    consumerForm.rule.list.splice(index, 1);
  }
};
// 选择优惠券
const couponRef = ref<InstanceType<typeof CouponDialog> | null>(null);
const visible = ref(false);
const dialogTableList = ref<any[]>([]);
const openCouponList = async (index: number, isSelect: boolean, parameter?: any) => {
  const res = await getFoodCouponList({ pageNum: 1, pageSize: 99999, isAvailable: true, ...parameter });
  dialogTableList.value = JSON.parse(JSON.stringify(res.data.list));

  if (isSelect) {
    dialogTableList.value.forEach((v, i) => {
      consumerForm.rule.list[index].couponList.forEach(e => {
        if (e.id === v.id) {
          dialogTableList.value[i].isSelected = true;
        }
      });
    });
  }
  couponRef.value?.acceptParams({
    tableData: isSelect ? dialogTableList.value : res.data.list,
    title: "优惠券列表",
    index,
    columns: [
      { type: "selection" },
      { prop: "name", label: "活动名称", width: 180 },
      { prop: "typeName", label: "券类型", width: 100 },
      { prop: "startDate", label: "开始时间" },
      { prop: "endDate", label: "结束时间" },
      { prop: "validityDesc", label: "领取后有效期" }
    ],
    search: {
      label: "券名称：",
      type: "input",
      searchLabel: "券类型",
      mate: [
        { label: "代金券", value: 1 },
        { label: "商品兑换券", value: 2 },
        { label: "折扣券", value: 3 }
      ]
    }
  });
};
const selectCoupon = (e: any) => {
  // 选中优惠券
  consumerForm.rule.list[e.index].couponList = e.tableData;
};
const onDelCoupon = (ruleIndex: number, couponIndex: number) => {
  // 删除优惠券
  consumerForm.rule.list[ruleIndex].couponList.splice(couponIndex, 1);
};

// 切换选中某种奖励
const onChangeAward = (type: string, index: number) => {
  if (type === "amount") {
    consumerForm.rule.list[index].giftAmount = 0;
  } else if (type === "point") {
    consumerForm.rule.list[index].pointValue = 0;
    consumerForm.rule.list[index].pointType = 2;
  } else {
    consumerForm.rule.list[index].couponList = [];
  }
};

// 搜索优惠券
const searchCoupon = (e: any) => {
  openCouponList(e.index, true, { name: e.searchText, typeId: e.searchType || null });
};
const onReset = (e: any) => {
  openCouponList(e.index, true, {});
};

// 修改可用会员门店
const onChangeMember = (type: string) => {
  if (type === "member") {
    consumerForm.gradeList = [];
  } else {
    consumerForm.storeList = [];
  }
};

// 获取会员数组
const memberList = ref<any[]>([]);
const getMemberList = async () => {
  const res = await getMemberGradeList({ pageNum: 1, pageSize: 9999 });
  memberList.value = JSON.parse(JSON.stringify(res.data.list));
  if (route.query.id) {
    memberList.value.forEach(v => {
      consumerForm.gradeList!.forEach((i: any) => {
        if (v.id === i.id) {
          v.checked = true;
        }
      });
    });
  }
};
// const storeList = ref<any[]>([]);
// const onGetStoreList = async () => {
//   const res = await getStoreList({ pageNum: 1, pageSize: 9999 });
//   storeList.value = res.data.list;
// };

onMounted(async () => {
  // Promise.all([getMemberList(), onGetStoreList()]);
  if (route.query.id) {
    const res = await getConsumerDetailAPI({ id: route.query.id });
    Object.keys(consumerForm).forEach(key => {
      if (res.data?.hasOwnProperty(key)) {
        consumerForm[key] = JSON.parse(JSON.stringify(res.data[key]));
      }
    });
  }
  getMemberList();
});
</script>

<template>
  <div class="consumerRebate-container">
    <HeaderCard
      :is-show-button="route.query.type === 'view' ? false : true"
      @confirm="onsubmit"
      @back="router.go(-1)"
      :title="(!route.query.id ? '新增' : route.query.type === 'view' ? '查看' : '编辑') + '消费满额赠礼'"
    ></HeaderCard>
    <div class="main">
      <div class="result">
        <img src="@/assets/images/consumerRebate.png" alt="" />
      </div>
      <div class="collection">
        <el-form :rules="rules" label-width="120" ref="formRef" :model="consumerForm" style="width: 70%; padding: 10px">
          <div class="title">活动基础信息</div>
          <div class="content" style="width: 60%">
            <el-form-item label="活动名称：" prop="name">
              <el-input v-model="consumerForm.name"></el-input>
            </el-form-item>
            <el-form-item label="活动编码：" prop="code">
              <el-input v-model="consumerForm.code"></el-input>
            </el-form-item>
            <el-form-item label="自定义日期：" prop="validityRange">
              <el-date-picker
                v-model="consumerForm.validityRange"
                format="YYYY-MM-DD"
                type="daterange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
              />
            </el-form-item>

            <el-form-item label="备注:" prop="remark">
              <el-input v-model="consumerForm.remark" type="textarea"></el-input>
            </el-form-item>

            <el-form-item label="可用周期：" prop="">
              <!-- v-model="consumerForm.cycleType" @change="onChangeCycleType" prop="cycleType"-->
              <el-radio-group v-model="consumerForm.cycleType" @change="onChangeCycle">
                <el-radio :value="0" size="large">每天</el-radio>
                <el-radio :value="1" size="large">每周</el-radio>
                <el-radio :value="2" size="large">每月</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item
              prop="cycleValue"
              v-if="consumerForm.cycleType === 1"
              :rules="consumerForm.cycleType === 1 ? rules.cycleValue : [{ required: false }]"
            >
              <div class="select-day-in-week-wrapper">
                <el-checkbox-group v-model="consumerForm.cycleValue">
                  <el-checkbox v-for="cycle in cycleData" :key="cycle.value" :value="cycle.value">{{ cycle.label }}</el-checkbox>
                </el-checkbox-group>
              </div>
            </el-form-item>
            <el-form-item
              prop="cycleValue"
              v-if="consumerForm.cycleType === 2"
              :rules="consumerForm.cycleType === 2 ? rules.cycleValue : [{ required: false }]"
            >
              <div class="select-day-in-week-wrapper">
                <el-checkbox-group v-model="consumerForm.cycleValue">
                  <el-checkbox v-for="day in 31" :key="'day' + day" :value="day">{{ day < 10 ? "0" + day : day }}</el-checkbox>
                </el-checkbox-group>
              </div>
            </el-form-item>
          </div>

          <div>参与规则</div>
          <div class="content">
            <!-- <el-form-item label="适用门店：">
              <el-radio-group v-model="consumerForm.storeType" @change="onChangeMember('store')">
                <el-radio :value="0">全部门店</el-radio>
                <el-radio :value="1">指定门店</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="指定适用门店：" v-if="consumerForm.storeType">
              <el-checkbox-group v-model="consumerForm.storeList">
                <el-checkbox v-for="item in storeList" :value="item.id" :key="item.id">{{ item.storeName }}</el-checkbox>
              </el-checkbox-group>
            </el-form-item> -->
            <el-form-item label="适用会员：">
              <el-radio-group v-model="consumerForm.gradeType" @change="onChangeMember('member')">
                <el-radio :value="0">全部会员</el-radio>
                <el-radio :value="1">指定会员</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="指定会员选择:" v-if="consumerForm.gradeType">
              <el-checkbox-group v-model="consumerForm.gradeList">
                <el-checkbox
                  :checked="item.checked"
                  :label="item.title"
                  :value="item.id"
                  v-for="item in memberList"
                  :key="item.id"
                />
              </el-checkbox-group>
            </el-form-item>
          </div>

          <div>活动规则</div>
          <div class="content">
            <el-form-item label="赠送规则：" prop="rule.ruleType">
              <el-radio-group @change="changeRuleList('ruleType', 0)" v-model="consumerForm.rule.ruleType">
                <!--  最少一个-->
                <el-radio :value="1">消费满额赠送</el-radio>
                <!-- 有且只能有一个 -->
                <el-radio :value="2">消费每满额赠送</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item prop="rule.list">
              <div class="activity-table" v-for="(item, index) in consumerForm.rule.list" :key="index">
                <div class="header">
                  <div>规则{{ index + 1 }}：</div>
                  <div @click="changeRuleList('del', index)" style="cursor: pointer">删除</div>
                </div>
                <!-- 表格内容 -->
                <div class="activity-info">
                  <el-form-item
                    label="消费满"
                    label-width="70"
                    :prop="`rule.list[${index}].amount`"
                    :rules="[
                      { required: true, message: '请输入' },
                      { validator: validateAmount, trigger: ['blur'] }
                    ]"
                  >
                    <el-input-number :min="0" v-model="item.amount" style="width: 40%" controls-position="right">
                      <template #append> 元 </template>
                    </el-input-number>
                    <span style="margin-left: 10px">获得以下奖励</span>
                    <span style="margin-left: 10px; color: #cccccc">奖励最少选填一种</span>
                  </el-form-item>
                  <el-form-item
                    style="margin-top: 20px"
                    label-width="0"
                    :prop="`rule.list[${index}].giftAmount`"
                    :rules="
                      item.isGiftAmount
                        ? [
                            { required: true, message: '请输入' },
                            { validator: giftAmountValidator, trigger: 'blur' }
                          ]
                        : [{ required: false }]
                    "
                  >
                    <el-checkbox @change="onChangeAward('amount', index)" v-model="item.isGiftAmount" label="金额奖励" />
                    <div v-if="item.isGiftAmount">
                      <span style="margin: 0 10px">赠送储值金额</span>
                      <el-input-number :min="0" controls-position="right" v-model="item.giftAmount" style="width: 40%">
                        <!-- <template #append> 元 </template> -->
                      </el-input-number>
                      <span style="margin-left: 5px; color: #cccccc">元</span>
                    </div>
                  </el-form-item>
                  <el-form-item v-if="item.isGiftAmount" label-width="88">
                    <div style="color: #999999">赠送金额进入储值赠送账户余额</div>
                  </el-form-item>

                  <el-form-item
                    style="margin-top: 20px"
                    label-width="0"
                    :prop="`rule.list[${index}].pointValue`"
                    :rules="
                      item.isGiftPoint
                        ? [
                            { required: true, message: '请输入' },
                            { validator: giftPointValidator, trigger: 'blur' }
                          ]
                        : [{ required: false }]
                    "
                  >
                    <el-checkbox v-model="item.isGiftPoint" @change="onChangeAward('point', index)" label="积分奖励" />
                    <el-input v-model="item.pointValue" v-if="item.isGiftPoint" style="width: 60%; margin-left: 10px">
                      <template #prepend>
                        <el-select v-model="item.pointType" style="width: 200px">
                          <el-option label="按比例返回积分" :value="1" />
                          <el-option label="返回固定积分" :value="2" />
                        </el-select>
                      </template>
                      <template #append> % </template>
                    </el-input>
                  </el-form-item>

                  <el-form-item
                    style="margin-top: 20px"
                    label-width="0"
                    :prop="`rule.list[${index}].couponList`"
                    :rules="item.isGiftCoupon ? [{ required: true, message: '请选择', trigger: 'blur' }] : [{ required: false }]"
                  >
                    <el-checkbox @change="onChangeAward('coupon', index)" label="优惠券奖励" v-model="item.isGiftCoupon" />
                    <div v-if="item.isGiftCoupon">
                      <span
                        @click="openCouponList(index, false)"
                        v-if="item.couponList.length < 1"
                        style="margin: 0 10px; color: #ff6000; cursor: pointer"
                      >
                        添加优惠券
                      </span>
                      <span @click="openCouponList(index, true)" v-else style="margin: 0 10px; color: #ff6000; cursor: pointer">
                        已选择{{ item.couponList.length }}种优惠券
                      </span>
                    </div>
                  </el-form-item>

                  <el-form-item label-width="70" v-if="item.couponList.length > 0">
                    <el-table border :data="item.couponList">
                      <el-table-column label="序号" width="60">
                        <template #default="{ $index }">
                          {{ $index + 1 }}
                        </template>
                      </el-table-column>
                      <el-table-column prop="id" label="券模版Id"></el-table-column>
                      <el-table-column width="100" prop="name" label="券名称"></el-table-column>
                      <el-table-column label="券数量" width="130">
                        <template #default="{ row }">
                          <el-input-number
                            style="width: 100px"
                            :min="0"
                            v-model="row.count"
                            controls-position="right"
                          ></el-input-number>
                        </template>
                      </el-table-column>
                      <el-table-column width="80" fixed="right" label="操作">
                        <template #default="{ $index }">
                          <el-button type="text" @click="onDelCoupon(index, $index)">删除</el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                  </el-form-item>
                </div>
              </div>
              <el-button
                style="margin-top: 10px"
                type="primary"
                v-if="consumerForm.rule.ruleType === 1"
                @click="changeRuleList('add', 0)"
              >
                新增规则
                <text style="margin-left: 5px">{{ consumerForm.rule.list.length }}/10</text>
              </el-button>
            </el-form-item>

            <div class="activity-quantity">
              <el-form-item label="活动限次:">
                <div class="activity-box">
                  <div v-for="(item, index) in activityQuantityList" :key="item.name">
                    <div class="quantity-method">{{ item.name }}</div>
                    <div class="input-quantity">
                      <el-radio-group v-model="consumerForm[item.isName]" @change="onChangeQuantity(item.isName, index)">
                        <el-radio :value="false">不限制</el-radio>
                        <el-radio :value="true">限制</el-radio>
                      </el-radio-group>
                      <el-form-item v-if="consumerForm[item.isName]" label-width="10" :prop="item.prop">
                        <el-input-number :min="1" controls-position="right" v-model="consumerForm[item.prop]"></el-input-number>
                      </el-form-item>
                    </div>
                  </div>
                </div>
              </el-form-item>
            </div>
          </div>
        </el-form>
      </div>
    </div>
    <CouponDialog ref="couponRef" @on-reset="onReset" @on-search="searchCoupon" @on-confirm="selectCoupon"></CouponDialog>
  </div>
</template>

<style lang="scss" scoped>
div {
  box-sizing: border-box;
}
.consumerRebate-container {
  height: 100%;
  overflow: hidden;
  background-color: #ffffff;
  .main {
    display: flex;
    height: calc(100% - 72px);
    padding: 20px;
    overflow-y: auto;
    .result {
      width: 300px;
      height: calc(100% - 40px);
      img {
        width: 100%;
        height: 100%;
      }
    }

    // 输入信息
    .collection {
      flex: 1;
      height: calc(100% - 10px);
      padding-left: 20px;
      overflow-y: auto;
      .content {
        margin-top: 10px;

        // background-color: #cccccc;
        .activity-table {
          width: 100%;
          margin-top: 15px;
          .header {
            display: flex;
            justify-content: space-between;
            padding: 0 20px;
            color: #333333;
            border-collapse: collapse;
            border: 1px solid #e8e8e8;
          }
          .activity-info {
            min-height: 200px;
            padding: 20px;
            border: 1px solid #e8e8e8;
          }
        }
        .activity-quantity {
          .activity-box {
            width: 100%;
            height: 250px;
            border: 1px solid #e8e8e8;
            & > div {
              display: flex;
              height: 33.33%;
              & > div {
                height: 100%;
                font-size: 16px;
                line-height: 84px;
                border-collapse: collapse;
                border: 1px solid #e8e8e8;
              }
              .quantity-method {
                width: 35%;
                padding-left: 20px;
                background-color: #fafafa;
              }
              .input-quantity {
                display: flex;
                flex: 1;
                align-items: center;
                padding-left: 20px;
              }
            }
          }
        }
      }
    }
  }
}
</style>
